home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 15243 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: news.ccs.queensu.ca!news
  2. From: Wintermute <3mal5@qlink.queensu.ca>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Array declaration
  5. Date: Thu, 04 Apr 1996 07:29:27 -0500
  6. Organization: System Infinity
  7. Message-ID: <3163C0A7.2BBF@qlink.queensu.ca>
  8. References: <4jvo2g$mp2@hermes.is.co.za>
  9. NNTP-Posting-Host: qlink.queensu.ca
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (X11; I; qlink 5.4 sun4d)
  14.  
  15. Janine Prinsloo wrote:
  16. > I declared the following array:  dat[7][2048]
  17. > In the program I made the stupid mistake of using loops going from 1 to 7
  18. > and from 1 to 2048 instead of 0 to 6 and 0 to 2047. What I don't understand
  19. > is that the program ran fine for a number of times (the program is repeatedly
  20. > run by a batch program) before an error occurred.
  21. > I would like to know why an error didn't occur immediately the first time
  22. > the program was run.
  23. > Janine
  24.  
  25. C/++ offer no bounds checking on array accesses, whatsoever.  The array variable is
  26. merely a pointer to a byte in memory.  The index is merely a value that is added to
  27. the value of the array variable, which is the address of the first element of the
  28. array.
  29.  
  30. Suppose you declare an array of eight characters:
  31.  
  32. char dat[8];
  33.  
  34. dat is simply a 4-byte pointer to char, and its value is the memory address of the
  35. first byte of the eight that are allocated.
  36.  
  37. You can access those eight bytes using dat[0] to dat[7], but you could also use
  38. dat[-438] or dat[23422].  Your compiler may give you a warning if it is good, but
  39. there is nothing wrong with the code.
  40.  
  41. The problem is, you have no idea what is in the bytes that are not of the original 8
  42. you allocated.  You could be changing a global variable, or a return address, or
  43. even something in the operating system, probably wrecking your memory and producing
  44. a segmentation fault.
  45.  
  46. You can also do pointer arithmetic on dat, or cast it, but I digress.
  47.  
  48. The fix to this error is to ensure that you are ALWAYS within the bounds of your
  49. array.  You can do this by declaring consts that are the size of your array, and
  50. using them to limit indexing into the array, as in for statements.
  51.  
  52. Hope this helps.
  53.  
  54. --
  55. Wintermute  <3mal5@qlink.queensu.ca>  <http://qlink.queensu.ca/~3mal5/>
  56.  
  57. "If I really knew how to write, I could write something that someone 
  58. could read and it would kill them."  -  william s. burroughs
  59.